const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../utils/config.js'
import {
  reqConsumerDeviceBatchDel,
  reqConsumerRoomUpdate,
  reqConsumerDeviceMove
} from '../../../../request/api.js';

Page({
  data: {
    navMarginTop: app.globalData.navMarginTop + 'px', //导航栏高度
    navBarHeight: app.globalData.navBarHeight + 'px', //头部标题高度
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    deviceImg: '/statics/images/gaojing/yangan.png',

    dataList: [],

    deviceResult: [], //多选

    showRoomSelection: false,

  },

  onLoad(options) {
    this.getParams()
  },


  onShow() {

  },

  getParams() {
    const _this = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('sendDataToDevice', function (res) {
      _this.setData({
        dataList: res.data
      })
    })
  },

  getDataList() {

  },

  onChange(event) {
    this.setData({
      deviceResult: event.detail,
    });
  },

  toggle(event) {
    const {
      id
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${id}`);
    checkbox.toggle();
  },

  onChangeRoom() {
    const {
      deviceResult,
    } = this.data
    if (!(deviceResult && deviceResult.length)) return showMsg("请选择要修改的设备")
    this.setData({
      showRoomSelection: true
    })
  },

  async confirmRoomSelection(e) {
    const {
      action,
      roomInfo
    } = e.detail
    const {
      deviceResult,
      dataList
    } = this.data
    if (action == 'confirm') {
      // const params = {
      //   userId: app.globalData.userId,
      //   roomId: roomInfo.id,
      //   roomName: roomInfo.roomName,
      //   deviceCodeList: deviceResult
      // }
      // const res = await reqConsumerRoomUpdate(params)
      const res = await reqConsumerDeviceMove({
        deviceCodeList: deviceResult,
        roomId: roomInfo.id,
      })
      if (res.code !== 20000) return showMsg(res.message)

      dataList.forEach(item => {
        if (deviceResult.includes(item.deviceCode)) {
          item.roomId = roomInfo.id;
          item.roomName = roomInfo.roomName;
        }
      });
      this.setData({
        dataList,
        showRoomSelection: false
      })
      this.notifyPageUpdataFoo()
    } else {
      this.setData({
        showRoomSelection: false
      })
    }
  },


  async onDelete() {
    const {
      deviceResult,
      dataList
    } = this.data
    if (!(deviceResult && deviceResult.length)) return showMsg("请选择要移除的设备")

    Dialog.confirm({
      title: '温馨提示',
      message: '确认要移除选中的设备吗？',
    })
    .then(async () => {
      const res = await reqConsumerDeviceBatchDel({
        deviceCodeList: deviceResult
      })
      if (res.code !== 20000) return showMsg(res.message)
      const updatedDataList = dataList.filter(item => !deviceResult.includes(item.deviceCode));
      this.setData({
        dataList: updatedDataList,
        deviceResult: []
      })
      this.notifyPageUpdataFoo()
    })
    .catch(() => {});
  },

  notifyPageUpdataFoo() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('receiveDataFromDevice', {
      isUpdataList: true
    });
  },




  onFinish() {
    wx.navigateBack()
  },




  onMoveTop() {
    const {
      dataList,
      deviceResult
    } = this.data;

    const selectedDevices = dataList.filter(item => deviceResult.includes(item.id));
    const unselectedDevices = dataList.filter(item => !deviceResult.includes(item.id));

    // 2. 按 deviceResult 的顺序排序选中设备（保证"3,2,4"的顺序）
    const orderedSelectedDevices = [];
    deviceResult.forEach(id => {
      const device = selectedDevices.find(item => item.id === id);
      if (device) orderedSelectedDevices.push(device);
    });

    // 3. 合并数组并更新
    this.setData({
      dataList: [...orderedSelectedDevices, ...unselectedDevices]
    });
  },


})